import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Is_PUBLIC_KEY } from '../../common/decorators/public.decorator';
import { HandleTokenService } from './utils/handle-token';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private handleTokenService: HandleTokenService
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 检查是否为公开接口
    const isPublic = this.reflector.getAllAndOverride<boolean>(Is_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }

    /* 进行token的验证 - 成功会返回
    payload并设置request['user'],
    后面的这些接口需要验证的接口都会统一从request['user']中取数据
     */
    try {
      if (await this.handleTokenService.extractAndVerifyToken(context)) {
        return true;
      }
    } catch {
      return false;
    }
    return false;
  }
}
